package com.jxwifi.cloud.quickcleanserver.login;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.v4.content.LocalBroadcastManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.basicactivity.BasicActivity;
import com.bumptech.glide.Glide;
import com.idroid.utils.TextColorUtil;
import com.idroid.widget.LoadDialog;
import com.idroid.widget.Toaster;
import com.jxwifi.cloud.quickcleanserver.R;
import com.jxwifi.cloud.quickcleanserver.app.AccountMgr;
import com.jxwifi.cloud.quickcleanserver.app.CleanBasicActivity;
import com.jxwifi.cloud.quickcleanserver.app.StateUtils;
import com.jxwifi.cloud.quickcleanserver.app.UrlPool;
import com.jxwifi.cloud.quickcleanserver.bean.InfoBean;
import com.jxwifi.cloud.quickcleanserver.bean.SystemBean;
import com.jxwifi.cloud.quickcleanserver.captcha.CaptchaDialog;
import com.jxwifi.cloud.quickcleanserver.mycenter.AuthenticationActivity;
import com.jxwifi.cloud.quickcleanserver.okhttp.AuzHttp;
import com.jxwifi.cloud.quickcleanserver.okhttp.DataJson_Cb;
import com.jxwifi.cloud.quickcleanserver.okhttp.Params;
import com.jxwifi.cloud.quickcleanserver.utils.LocationGaoDe;
import com.jxwifi.cloud.quickcleanserver.utils.PasswordLogin;
import com.jxwifi.cloud.quickcleanserver.utils.ToastUtils;
import com.jxwifi.cloud.quickcleanserver.utils.TokenTimeUtils;
import com.popwindow.Popwindows;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.trinea.android.common.util.REPattern;

/**
 * Created by Administrator on 2019/5/11.
 */

public class LoginActivity extends CleanBasicActivity {

    @Bind(R.id.et_login_cleaning_phone)
    EditText mEtLoginCleaningPhone;//电话
    @Bind(R.id.et_login_cleaning_verification)
    EditText mEtLoginCleaningVerification;//验证码
    @Bind(R.id.tv_login_explain)
    TextView mTvLoginExplain;//协议书
    @Bind(R.id.tv_login_obtain_verification)
    TextView mTvLoginObtainVerification;//验证码按钮
    @Bind(R.id.img_selection_images)
    ImageView mImgSelectionImages;
    @Bind(R.id.tv_login_button)
    TextView mTvLoginButton;

    private boolean mIsSelection=true;
    private String mCustomer;//客服電話

    private CountDownTimer timer;
    private LoadDialog mLoadDialog;

    private String captchaCode;
    private String cutImage;
    private String srcImage;
    private int xposition;
    private int yposition;
    private boolean isNewUser = false;
    public Popwindows popwindow;
    private DisplayMetrics dm;
    private CaptchaDialog dialogshow;
    String verifyEffectiveToken;
    String verifyEffectiveCaptchaCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_cleaning);
        ButterKnife.bind(this);
        mLoadDialog = new LoadDialog(mBaseContext);
        openEventBus();
        initView();
    }

    public void initView(){
        mTvLoginButton.setClickable(false);
        if (!TextUtils.isEmpty(AccountMgr.getLastName(mBaseContext))) {
            mEtLoginCleaningPhone.setText(AccountMgr.getLastName(mBaseContext));
        }
        TextColorUtil.setTextColor(mBaseContext, mTvLoginExplain, "同意 《快洁帮用户协议》", " ", R.color.color_cleaning_text);

        mEtLoginCleaningPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                TextNull();
            }
        });

        mEtLoginCleaningVerification.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                TextNull();
            }
        });
    }
    @OnClick({R.id.tv_login_obtain_verification,R.id.tv_login_button,R.id.tv_login_explain,R.id.img_selection_images})
    void clickCK(View v){
        switch (v.getId()){
            //验证码按钮
            case R.id.tv_login_obtain_verification:
                validation();
                break;
            //登录
            case R.id.tv_login_button:
                if (mEtLoginCleaningPhone.getText().toString().equals("")) {
                    Toaster.show(mBaseContext, "请输入手机号码");
                    return;
                }
                boolean isMobile = REPattern.isMobileNO(mEtLoginCleaningPhone.getText().toString());
                if (!isMobile) {
                    Toaster.show(mBaseContext, "请输入正确的手机号码");
                    return;
                }
                if (mEtLoginCleaningVerification.getText().toString().equals("")) {
                    Toaster.show(mBaseContext, "验证码不能为空");
                    return;
                }
                //作保存手机号码的操作
                if (!TextUtils.isEmpty(mEtLoginCleaningPhone.getText().toString())) {
                    AccountMgr.putLastName(mBaseContext, mEtLoginCleaningPhone.getText().toString());
                }
                //接口请求
                datajson();
                break;
            case R.id.tv_login_explain:
                Intent intent=new Intent();
                intent.setClass(mBaseContext,UserloginActivity.class);
                startActivity(intent);
                break;
            case R.id.img_selection_images:
                if (mIsSelection){
                    mIsSelection=false;
                    mImgSelectionImages.setBackgroundResource(R.mipmap.icon_selectagreed_un);
                    //Glide.get(mBaseContext).clearMemory();
                    //LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(new Intent(EXITAPP));
                    //System.gc();
                }else{
                    mIsSelection=true;
                    mImgSelectionImages.setBackgroundResource(R.mipmap.icon_selection);
                }
                TextNull();
                break;
        }
    }

    public void TextNull(){
        if (!TextUtils.isEmpty(mEtLoginCleaningPhone.getText().toString())&&
                !TextUtils.isEmpty(mEtLoginCleaningVerification.getText().toString())&&mIsSelection){
            mTvLoginButton.setBackgroundResource(R.drawable.shap_bottom_buttom);
            mTvLoginButton.setClickable(true);
        }else{
            mTvLoginButton.setBackgroundResource(R.drawable.shap_bottom_buttom_no);
            mTvLoginButton.setClickable(false);
        }
    }

    public void validation(){
        if (mEtLoginCleaningPhone.getText().toString().equals("")) {
            Toaster.show(mBaseContext, "请输入手机号码");
            return;
        }
        boolean isMobile = REPattern.isMobileNO(mEtLoginCleaningPhone.getText().toString());
        if (!isMobile) {
            Toaster.show(mBaseContext, "请输入正确的手机号码");
            return;
        }
        mLoadDialog.show();
        isNewUserGet();
    }


    /**
     * 验证是否新用户
     * @return
     */
    private boolean isNewUserGet(){
        Params params = new Params();
        params.add("mobile", mEtLoginCleaningPhone.getText().toString());
        params.add("type", "CLEANER");
        AuzHttp.get(UrlPool.GET_VALIDATEUSER, params, new DataJson_Cb() {
            @Override
            public void onSuccess(int code, String data) {
                Log.i(TAG,"isNewUserGet ==> data = "+JSON.toJSON(data));
                JSONObject jsonObject = JSONObject.parseObject(data);
                //isNewUser = jsonObject.get("newUser");
                Log.i(TAG,"isNewUserGet ==> data = "+jsonObject.get("newUser"));

                if(jsonObject.get("newUser").equals(true)){
                    Log.i(TAG,"isNewUserGet ==> 新用户data = "+jsonObject.get("newUser"));
                    getVrifyImage();
                    //popCaptcha(mContext,captchaCode,cutImage,srcImage,xposition,yposition);

                }else{
                    mLoadDialog.dismiss();
                    Log.i(TAG,"isNewUserGet ==> 老用户data = "+jsonObject.get("newUser"));
                    setTimerCount();
                    String token = jsonObject.get("token").toString();
                    validateShortLetter(token,captchaCode);
                }

            }

            @Override
            public void onFailure(int errorCode, String msg) {

                mLoadDialog.dismiss();
                Log.i(TAG,"isNewUserGet ==> msg = "+msg+"请检查网络重试");
            }
        },TAG);
        return isNewUser;
    }

    /**
     * 获取验证码图片
     */
    public void getVrifyImage(){
        Params params = new Params();
        AuzHttp.get(UrlPool.GET_VERIFYIMAGE, params, new DataJson_Cb() {
            @Override
            public void onSuccess(int code, String data) {
                Log.i(TAG,"getVrifyImage() ==> data = "+JSON.toJSON(data));
                JSONObject jsonObject = JSONObject.parseObject(data);
                captchaCode = jsonObject.get("captchaCode").toString();
                cutImage = jsonObject.get("cutImage").toString();
                srcImage = jsonObject.get("srcImage").toString();
                xposition = Integer.parseInt(jsonObject.get("xposition").toString());
                yposition = Integer.parseInt(jsonObject.get("yposition").toString());
                mLoadDialog.dismiss();

                Log.i(TAG,"getVrifyImage ==>  yposition = "+yposition+" xposition = "+xposition);

                dm = getResources().getDisplayMetrics();
                Log.i(TAG, "屏幕尺寸： width = "+dm.widthPixels +" height = "+dm.heightPixels+" density = "+dm.densityDpi+" int ypositon = "+(int)(yposition * dm.densityDpi * 0.007));
                dialogshow = new CaptchaDialog(mBaseContext, captchaCode, cutImage, srcImage, xposition,(int)(yposition * dm.densityDpi * 0.0069),dm.densityDpi, new CaptchaDialog.CaptchaDialogListner() {
                    @Override
                    public void getX(int X) {
                        mLoadDialog.show();
                        verifyEffective((int)(X * 10000 / 69 / dm.densityDpi));
                    }

                    @Override
                    public void refresh() {
                        //点击刷新按钮
                        //getVrifyImage();
                        dialogshow.notify();
                    }

                });
                dialogshow.setCancelable(false);
                dialogshow.show();
            }

            @Override
            public void onFailure(int errorCode, String msg) {
                mLoadDialog.dismiss();
                Log.i(TAG,"getVrifyImage ==>AuzFailure  msg = "+msg);
            }
        },TAG);

    }


    /**
     * 验证图片是否成功
     * @param xposition
     */
    public void verifyEffective(int xposition){
        Params params = new Params();
        params.add("captchaCode", captchaCode);
        Log.i(TAG,"verifyEffective ==> xposition = "+xposition);
        params.add("xPosition", xposition);
        AuzHttp.get(UrlPool.GET_VERIFYIEDDEXTIVE, params, new DataJson_Cb() {
            @Override
            public void onSuccess(int code, String data) {
                Log.i(TAG,"isNewUserGet ==> data = "+JSON.toJSON(data));
                JSONObject jsonObject = JSONObject.parseObject(data);
                //isNewUser = jsonObject.get("newUser");
                Log.i(TAG,"verifyEffective ==>拼图验证成功 ");
                mLoadDialog.dismiss();
                Log.i(TAG,"verifyEffective ==> data = "+jsonObject.get("token"));
                verifyEffectiveToken = jsonObject.get("token").toString();
                verifyEffectiveCaptchaCode = jsonObject.get("captchaCode").toString();
                Toast.makeText(mBaseContext, "验证成功", Toast.LENGTH_SHORT).show();
                dialogshow.dismiss();
                successValidateShortLetter();

            }

            @Override
            public void onFailure(int errorCode, String msg) {
                mLoadDialog.dismiss();
                //getVrifyImage();
                if (errorCode == 409){
                    Toast.makeText(mBaseContext, "图形验证码过期，请重新获取", Toast.LENGTH_SHORT).show();
                    dialogshow.dismiss();
                }else{
                    Toast.makeText(mBaseContext, "验证失败", Toast.LENGTH_SHORT).show();
                    dialogshow.reset();
                }
                Log.i(TAG,"verifyEffective ==>AuzFailure  msg = "+msg);
            }
        },TAG);
    }

    public void successValidateShortLetter(){
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                setTimerCount();
                validateShortLetter(verifyEffectiveToken,verifyEffectiveCaptchaCode);
            }
        }, 1000);
    }


    /**
     * 请求短信验证码
     * @param token
     */
    private void validateShortLetter(String token,String captchaCode){
        Params params = new Params();
        params.add("mobile", mEtLoginCleaningPhone.getText().toString());
        params.add("token", token);
        params.add("type","LOGIN");
        AuzHttp.get(UrlPool.GET_VALIDATESHORTLETTER, params, new DataJson_Cb() {
            @Override
            public void onSuccess(int code, String data) {
                Log.i(TAG,"isNewUserGet ==> data = "+JSON.toJSON(data));
                JSONObject jsonObject = JSONObject.parseObject(data);
                //isNewUser = jsonObject.get("newUser");
                Log.i(TAG,"validateShortLetter ==>请求短信验证码 ");
                //Log.i(TAG,"validateShortLetter ==> data = "+jsonObject.get("msg"));
                //String token = jsonObject.get("token").toString();
                Toast.makeText(mBaseContext, "发送成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int errorCode, String msg) {
                Log.i(TAG,"validateShortLetter ==>AuzFailure  msg = "+msg);
                Toast.makeText(mBaseContext, msg, Toast.LENGTH_SHORT).show();
            }
        },TAG);
    }



    public void datajson(){
        mLoadDialog.show();
        mTvLoginButton.setClickable(false);
        mTvLoginButton.setBackgroundResource(R.drawable.shap_bottom_buttom_no);
        Params params=new Params();
        params.add("code",mEtLoginCleaningVerification.getText().toString());
        params.add("tell",mEtLoginCleaningPhone.getText().toString());
        AuzHttp.get(UrlPool.CLEANER_LOGIN, params, new DataJson_Cb() {
            @Override
            public void onSuccess(int code,String data) {
                if (code==0){
                    JSONObject obj = JSON.parseObject(data);
                    String token=obj.getString("token");
                    AccountMgr.puttoken(mBaseContext,token);
                    AuzHttp.KJB_APP_Token=AccountMgr.gettoken(mBaseContext);  //token添加到请求头
                    TokenTimeUtils.PreservationTime(mBaseContext);//记录下次更新的时间
                    String userInfo=obj.getString("userInfo");
                    InfoBean mInfoBean=JSON.parseObject(userInfo,InfoBean.class);
                    if ("Y".equals(mInfoBean.getIsFreeze())){//用户被冻结后提示不保存数据，不做登录记录
                        new AlertDialog.Builder(mBaseContext)
                                .setTitle("账户信息提醒")
                                .setMessage("您的账号已被冻结，请联系客服")
                                .setPositiveButton("拨打客服电话", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        //前往应用详情界面
                                        inittell();
                                        dialog.dismiss();
                                    }
                                }).create().show();
                        return;
                    }
                    if (TextUtils.isEmpty(mInfoBean.getLat())){
                        refreshlocation();
                    }
                    AccountMgr.putUser(mBaseContext,mInfoBean,true);
                    AccountMgr.loginSuccess(mBaseContext);
                    if (!StateUtils.YES.equals(AccountMgr.getIsAuth(mBaseContext))){
                        Intent intent=new Intent();
                        intent.setClass(mBaseContext, AuthenticationActivity.class);
                        startActivity(intent);
                        finish();
                    }
                    finish();
                    mTvLoginButton.setClickable(true);
                    mTvLoginButton.setBackgroundResource(R.drawable.shap_bottom_buttom);
                    mLoadDialog.dismiss();
                }
            }

            @Override
            public void onFailure(int errorCode, String msg) {

                Toast toast =Toast.makeText(mBaseContext, msg, Toast.LENGTH_SHORT);
                ToastUtils.showMyToast(toast,3000);
                mTvLoginButton.setClickable(true);
                mTvLoginButton.setBackgroundResource(R.drawable.shap_bottom_buttom);
                mLoadDialog.dismiss();
            }
        },TAG);
    }

    public void refreshlocation() {
        Params params = new Params();
        params.add("lon", LocationGaoDe.getLongitude());
        params.add("lat", LocationGaoDe.getLatitude());
        AuzHttp.get(UrlPool.UPDATE_REAL_LOCATION, params, new DataJson_Cb() {
            @Override
            public void onSuccess(int code,String data) {

            }

            @Override
            public void onFailure(int errorCode, String msg) {

            }
        }, "");
    }

    public void SendIdentCode(){
        Params params=new Params();
        params.add("mobile",mEtLoginCleaningPhone.getText().toString());
        params.add("type", "LOGIN");
        AuzHttp.get(UrlPool.POST_CAPTCHA_VALIDATE, params, new DataJson_Cb() {
            @Override
            public void onSuccess(int code,String data) {

            }

            @Override
            public void onFailure(int errorCode, String msg) {

                Toast toast =Toast.makeText(mBaseContext, msg, Toast.LENGTH_SHORT);
                ToastUtils.showMyToast(toast,3000);
            }
        },TAG);
    }
    //倒计时操作
    private void setTimerCount() {
        timer = new CountDownTimer(60 * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                mTvLoginObtainVerification.setText("验证码(" + millisUntilFinished / 1000 + "s)");
                mTvLoginObtainVerification.setEnabled(false);
            }

            @Override
            public void onFinish() {
                timer.cancel();
                mTvLoginObtainVerification.setEnabled(true);
                mTvLoginObtainVerification.setText("重获验证码");
            }
        };
        timer.start();
    }

    public void inittell() {
        Params params = new Params();
        AuzHttp.get(UrlPool.SYSTEM_LIST, params, new DataJson_Cb() {
            @Override
            public void onSuccess(int code, String data) {
                if (code == 0) {//正常数据
                    List<SystemBean> msystemBean = JSON.parseArray(data, SystemBean.class);
                    for (int i = 0; i < msystemBean.size(); i++) {
                        if ("kjb_ke_tell".equals(msystemBean.get(i).getKeyName())) {
                            mCustomer = msystemBean.get(i).getKeyValue();
                            break;
                        }
                    }
                    if (!TextUtils.isEmpty(mCustomer)) {
                        Intent mTelintent = new Intent(Intent.ACTION_DIAL);
                        Uri Urldata = Uri.parse("tel:" + mCustomer.replace("\\", ""));
                        mTelintent.setData(Urldata);
                        startActivity(mTelintent);
                    }
                } else {//请他情况做密码登录接口请求操作后再次请求接口
                    PasswordLogin.passwordlogin(mBaseContext, TAG, AccountMgr.gettell(mBaseContext), AccountMgr.getpassword(mBaseContext));
                    if (PasswordLogin.mIsLogin) {
                        inittell();
                    }
                }
            }

            @Override
            public void onFailure(int errorCode, String msg) {

                Toast toast =Toast.makeText(mBaseContext, msg, Toast.LENGTH_SHORT);
                ToastUtils.showMyToast(toast,3000);
            }
        }, TAG);
    }



}
